import 'dart:convert';
import 'dart:ui';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../../http/Api.dart';
import '../../http/HttpUtil.dart';
import '../../util/SignUtil.dart';
import '../../base/Constant.dart';
import '../../util/AppSaveInfoUtil.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import '../../entity/collect_brand_list_entity.dart';

class CollectBrandListPage extends StatefulWidget {
  CollectBrandListPage({Key key}) : super(key: key);

  @override
  _CollectBrandListPageState createState() => _CollectBrandListPageState();
}

class _CollectBrandListPageState extends State<CollectBrandListPage> {
  List<BrandModelData> homeListData = new List();
  var _scaffoldKey = new GlobalKey<ScaffoldState>();
  GlobalKey _stackKey = GlobalKey();
  EasyRefreshController _controller = new EasyRefreshController();
  int page = 1;
  int currentShow = 0; //0 正常 1 网格
  String token;
  final SlidableController slidableController = SlidableController();
  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    return Container(
      child:  new Stack(
            key: _stackKey,
            children: <Widget>[
              new Column(
                children: <Widget>[
                  new Container(
                    height: MediaQuery.of(context).size.height -
                        kToolbarHeight -
                        ScreenUtil.getInstance().setHeight(DP_120) -
                        MediaQueryData.fromWindow(window).padding.top,
                    color: f0Color,
                    child: new EasyRefresh(
                      controller: _controller,
                      header: MaterialHeader(),
                      footer: MaterialFooter(),
                      enableControlFinishLoad: true,
                      enableControlFinishRefresh: true,
                      child: ListView.separated(
                              itemBuilder: _renderRow,
                              separatorBuilder:
                                  (BuildContext context, int index) {
                                return Container(
                                  color: divideColor,
                                  height: 1,
                                );
                              },
                              itemCount: homeListData == null
                                  ? 0
                                  : homeListData.length),
                          
                      onRefresh: () async {
                        page = 1;
                        loadList();
                      },
                      onLoad: () async {
                        page++;
                        loadList();
                      },
                    ),
                  ),
                ],
              ),
            ],
          ),
    );
  }

  Widget _renderRow(BuildContext context, int index) {
    var price = RichText(
      textAlign: TextAlign.left,
      text: TextSpan(style: TextStyle(color: Colors.red), children: [
        TextSpan(text: '¥', style: TextStyle(fontSize: 12.0)),
        TextSpan(
            text: '', style: TextStyle(fontSize: 18.0)),
        TextSpan(
          text: '',
          style: TextStyle(
              fontSize: 12.0,
              color: Colors.grey,
              decoration: TextDecoration.lineThrough,
              decorationColor: Colors.grey),
        ),
      ]),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
    return Slidable(
        actionPane: SlidableStrechActionPane(),
        controller: slidableController,
        actionExtentRatio: 0.25,
        secondaryActions: <Widget>[
          IconSlideAction(
            caption: '取消收藏',
            color: Colors.red,
            icon: Icons.delete,
            closeOnTap: true,
            onTap: () {
              del(homeListData[index].brand_id);
            },
          ),
        ],
        child:  new GestureDetector(
      onTap: () {
        //处理点击事件
        // GoodsModelData model = homeListData[index];

        // Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
        //   return GoodsDetailPage(
        //     goods_id: model.goods_id,
        //     img: model.img,
        //   );
        // }));
      },
      child: Container(
        padding: EdgeInsets.all(10),
        color: white,
        child: new Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            homeListData[index].logo == ""
                ? Image.asset('images/pic_default.png',
                    width: ScreenUtil.getInstance().setWidth(80),
                    fit: BoxFit.fill,
                    height: ScreenUtil.getInstance().setWidth(80))
                : Image.network(
                    Api.ImgBaseUrl+homeListData[index].logo,
                    width: ScreenUtil.getInstance().setHeight(80),
                    height: ScreenUtil.getInstance().setHeight(80),
                    fit: BoxFit.fill,
                  ),
            Expanded(
              flex: 1,
              child: Container(
                padding: EdgeInsets.fromLTRB(10, 5, 5, 5),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      homeListData[index].name,
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          fontSize: ScreenUtil.getInstance().setSp(28),
                          color: black,
                          fontWeight: FontWeight.w400),
                    ),
                    Row(
                      children: <Widget>[
                        Expanded(
                          flex: 1,
                          child: Text(
                            homeListData[index].introduce=='null'?'':homeListData[index].introduce),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    ));
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getString(TOKEN).then((value) {
      token = value;
      if (value == null) {
        Navigator.of(context).pushNamed('login');
      } else {
        loadList();
      }
    });
  }

  loadList() async {
    Map map = new Map.from({
      "sign_type": createSignType(Api.URL_BrandCollect_getCollectList),
      "token": token,
    });
    Response<String> response =
        await HttpUtil().post(Api.URL_BrandCollect_getCollectList, data: getSign(map));
         print(response);
    Map userMap = json.decode(response.data);
    print(userMap);
    BrandModelEntity itemEntity = new BrandModelEntity.fromJson(userMap);
    print(userMap);
    if (itemEntity.code == 1) {
      if (mounted) {
        setState(() {
          if (page == 1) {
            homeListData.clear();
            homeListData = itemEntity.data;
          } else {
            homeListData.addAll(itemEntity.data);
          }
        });
      }
    }
  }
  del(String brand_id)async{
    Map map = new Map.from({
      "sign_type": createSignType(Api.URL_BrandCollect_cancel),
      "token": token,
      'brand_id':brand_id
    });
    Response<String> response =
        await HttpUtil().post(Api.URL_BrandCollect_cancel, data: getSign(map));
        Map userMap = json.decode(response.data);
        if (userMap['code'] == 1&&mounted) {
loadList();
        }
  }
}